package com.cf.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cf.domain.pojo.JudgesScore;
import com.cf.domain.pojo.JudgesScoreOptions;
import com.cf.domain.vo.ScoreOptionsVO;
import com.cf.domain.vo.ScoreVO;
import com.cf.mapper.ScoreMapper;
import com.cf.service.IJudgesScoreOptionsService;
import com.cf.service.IJudgesScoreService;
import com.cf.service.IScoreService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author lzqinga@126.com
 * @Date 2024/11/11  13:51
 */
@Service
@RequiredArgsConstructor
public class ScoreServiceImpl extends ServiceImpl<ScoreMapper, ScoreVO> implements IScoreService {

    private final IJudgesScoreService judgesScoreService;

    private final IJudgesScoreOptionsService judgesScoreOptionsService;
    @Override
    public void score(ScoreVO scoreVO) {
        //评委给团队打的总分
        Integer total = 0;
        for(ScoreOptionsVO option:scoreVO.getList()){
            //累计增加分数
            total += option.getScore();
        }

        JudgesScore judgesScore = new JudgesScore();
        judgesScore.setUserId(scoreVO.getUserId());
        judgesScore.setJudgesId(scoreVO.getJudgesId());
        judgesScore.setScore(total);
        judgesScoreService.save(judgesScore);

        List<JudgesScoreOptions> list = getJudgesScoreOptions(scoreVO, judgesScore);
        judgesScoreOptionsService.saveBatch(list);

        //团队打分持久化
//        TeamScore teamScore = new TeamScore();
//        teamScore.setUserId(scoreVO.getUserId());
//        teamScore.setJudgesId(scoreVO.getJudgesId());
//        teamScore.setAverageScore(averageScore(total));
//        teamScore.setScore(total);
//        teamScoreService.save(teamScore);
    }

    private static List<JudgesScoreOptions> getJudgesScoreOptions(ScoreVO scoreVO, JudgesScore judgesScore) {
        List<JudgesScoreOptions> list = new ArrayList<>();
        for(ScoreOptionsVO option: scoreVO.getList()){
            //每个细分项打分持久化
            JudgesScoreOptions judgesScoreOptions = new JudgesScoreOptions();
            judgesScoreOptions.setJudgesScoreId(judgesScore.getId());
            judgesScoreOptions.setScore(option.getScore());
            judgesScoreOptions.setJudgesId(scoreVO.getJudgesId());
            judgesScoreOptions.setUserId(scoreVO.getUserId());
            judgesScoreOptions.setScoreOptionsId(option.getId());
            list.add(judgesScoreOptions);
        }
        return list;
    }

    private Double averageScore(Integer sum){
        BigDecimal result = new BigDecimal(sum/3);
        return result.setScale(2, RoundingMode.HALF_UP).doubleValue();
    }
}
